<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="88px">
      <el-form-item label="设备名称" prop="terminalName">
        <el-input
          v-model="queryParams.terminalName"
          placeholder="请输入设备名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属代理商" prop="agentUid">
        <el-select v-model="queryParams.agentUid" clearable>
          <el-option
            v-for="item in agentList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="所属门店" prop="storeUid">
        <el-select v-model="queryParams.storeUid" clearable>
          <el-option
            v-for="item in storeList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="设备状态" prop="online">
         <el-select v-model="queryParams.online" clearable>
          <el-option
            v-for="item in onlineList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="所属车队" prop="agentUid">
        <!-- <el-select v-model="queryParams.fleetUid" clearable> -->
        <el-select v-model="queryParams.terminalFleetName" clearable>
          <!-- <el-option
            v-for="item in FleetList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          /> -->
          <el-option
            v-for="item in FleetList"
            :key="item.label"
            :label="item.label"
            :value="item.label"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
         <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button @click="resetQuery">重置</el-button>
        <el-button type="primary" @click="handleQuery">查询</el-button>
      </el-form-item>
    </el-form>
    <el-form size="small">
      <el-form-item>
        <el-button type="primary" @click="add">添加终端</el-button>
        <el-button type="primary" @click="bindTerminal">绑定终端</el-button>
        <el-button type="primary" @click="edit1">编辑</el-button>
        <el-button @click="delbatch" style="border: 1px solid #FF5555;color:#FF5555">删除</el-button>
      </el-form-item>
    </el-form>
    <el-table
      v-loading="loading"
      :data="list"
      style="width: 100%;"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="50"></el-table-column>
      <el-table-column label="序号" type="index" >
        <template slot-scope="scope">
          <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
        </template>
      </el-table-column>
      <el-table-column label="设备名称"  prop="terminalName" />
      <el-table-column label="设备编号"  prop="terminalNo" />
      <el-table-column label="所属代理商"  prop="nickName" />
      <el-table-column label="出货数量(今日/本月)"  prop="" >
        <template slot-scope="scope">
          {{scope.row.currDayFillCount}} / {{ scope.row.currMonthFillCount}}
        </template>
      </el-table-column>
      <el-table-column label="所属门店"  prop="storeUserName" />
      <el-table-column label="设备状态" >
        <template slot-scope="scope">
          <span style="color:#3FE46D" v-show="scope.row.online == '1'">在线</span>
          <span style="color:#FF5555" v-show="scope.row.online == '0'">离线</span>
        </template>
      </el-table-column>
      <el-table-column label="所属车队"  prop="terminalFleetName" />
      <el-table-column label="创建时间"  prop="createdTime" />
      <el-table-column label="操作" >
        <template slot-scope="scope">
          <el-button type="text" style="color:#386BD7" @click="look(scope.row)">查看二维码</el-button>
          <el-button type="text" style="color:#386BD7" @click="edit(scope.row)">编辑</el-button>
          <el-button type="text" style="color:#FF5555" @click="del(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
    <!-- 添加 修改终端 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="140px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="终端名称" prop="terminalName">
              <el-input v-model="form.terminalName" placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="终端编号" prop="terminalNo">
              <el-input v-model="form.terminalNo" placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备容量" prop="capacity">
              <el-input v-model="form.capacity" @input="val=>form1.capacity=val.replace(/[^\d]/g,'')" placeholder="请输入">
                <span slot="suffix">L</span>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="超时时间(秒）" prop="timeout">
              <el-input v-model="form.timeout" @input="val=>form1.timeout=val.replace(/[^\d]/g,'')" placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备系数" prop="pulse">
              <el-input v-model="form.pulse" @input="val=>form1.pulse=val.replace(/[^\d]/g,'')" placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单价(分)" prop="price">
              <el-input v-model="form.price" @input="val=>form1.price=val.replace(/[^\d]/g,'')" placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="agentList.length > 0">
            <el-form-item label="所属代理商" prop="agentUid">
              <el-select v-model="form.agentUid" clearable style="width:100%">
                <el-option
                  v-for="item in agentList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属门店" prop="storeUid">
              <el-select v-model="form.storeUid" clearable style="width:100%">
                <el-option
                  v-for="item in storeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="模式" prop="model">
              <el-select v-model="form.model" clearable style="width:100%">
                <el-option
                  v-for="item in modelList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 绑定终端 -->
    <el-dialog title="绑定终端" :visible.sync="open1" width="400px" append-to-body>
      <el-form ref="form1" :model="form1" :rules="rules1" label-width="80px">
        <el-form-item label="所属车队" prop="fleetId">
          <el-select v-model="form1.fleetId" style="width:100%" clearable>
            <el-option
              v-for="item in FleetList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="绑定终端" :required="true">
          <el-select 
          v-model="terminalSelection"
          multiple
          filterable
          remote
          reserve-keyword
          placeholder="请选择终端"
          :remote-method="remoteMethod" 
          clearable
          style="width:100%">
            <el-option
              v-for="item in terminalList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="折扣率" prop="discount">
          <el-input v-model="form1.discount" @input="val=>form1.discount=val.replace(/[^\d.]/g,'')" placeholder="请输入">
            <span slot="suffix">%</span>
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="bindcancel">取 消</el-button>
        <el-button type="primary" @click="bindConfirm">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog
    title="提示"
    :visible.sync="delVisible"
    width="30%">
    <span>是否删除该终端？</span>
    <span slot="footer" class="dialog-footer">
      <el-button @click="delVisible = false">取 消</el-button>
      <el-button type="primary" @click="delConfirm">确 定</el-button>
    </span>
  </el-dialog>
  <el-dialog
    title="二维码"
    :visible.sync="openCode"
    width="30%">
    <img :src="vSrc" style="width:100%" alt="">
    <span>终端编号：{{ qrterminalCode }}</span>
  </el-dialog>
  </div>
</template>

<script>
import { getTerminalList,addTerminal,updateTerminal,getAgentList,delTerminal,getFleetInfoList,bindTerminal,getTerminalCode } from "@/api/common";

export default {
  name: "Online",
  data() {
    return {
      vSrc:'',
      qrterminalCode:'',
      openCode:false,
      delVisible:false,
      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      // 表格数据
      list: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        params:{}
      },
      modelList:[
        {value:0,label:'联网'},
        {value:1,label:'脱机'}
      ],
      onlineList:[
        {value:'1',label:'在线'},
        {value:'0',label:'离线'}
      ],
      terminalSelection:[],
      terminalList:[],
      FleetList:[],
      agentList:[],
      storeList:[],
      selection:[],
      form:{},
      form1:{},
      rules: {
        terminalName: [
          { required: true, message: "终端名称不能为空", trigger: "blur" }
        ],
        terminalNo: [
          { required: true, message: "终端编号不能为空", trigger: "blur" }
        ],
        capacity: [
          { required: true, message: "设备容量不能为空", trigger: "blur" }
        ],
        timeout:[
          { required: true, message: "超时时间不能为空", trigger: "blur" }
        ],
        pulse:[
          { required: true, message: "设备系数不能为空", trigger: "blur" }
        ],
        price:[
          { required: true, message: "单价不能为空", trigger: "blur" }
        ],
        model:[
          { required: true, message: "模式不能为空", trigger: "blur" }
        ],
      },
      rules1:{
        fleetId: [
          { required: true, message: "所属车队不能为空", trigger: "blur" }
        ],
        discount: [
          { required: true, message: "折扣率不能为空", trigger: "blur" }
        ],
      },
      title:'',
      open:false,
      open1:false,
      dateRange:[]
    };
  },
  created() {
    this.getAgent()
    this.getStore()
    this.getFleet()
    this.getList();
  },
  watch:{
    dateRange(val){
      console.log(val)
      if(val){
        this.queryParams.params.startDate = val[0]
        this.queryParams.params.endDate = val[1]
      }else{
        this.queryParams.params = {}
      }
    }
  },
  methods: {
    remoteMethod(val){
      let queryParams = {
        pageNum: 1,
        pageSize: 10,
        terminalName:val
      }
      if(val) queryParams.terminalName = val
      getTerminalList(queryParams).then(response => {
        this.terminalList = response.rows.map(item=>{
          return{
            label:item.terminalName,
            value:item.id
          }
        })
      });
    },
    getFleet(){
      getFleetInfoList().then(res=>{
        if(res.code == 200){
          this.FleetList = res.data.map(item=>{
            return{
              label:item.fleetName,
              value:item.id
            }
          })
        }
      })
    },
    getStore(){
      let req = {
        userType:'04'
      }
      getAgentList(req).then(res=>{
        if(res.code == 200){
          this.storeList = res.rows.map(e=>{
            return{
              label:e.nickName,
              value:e.userId
            }
          })
        }
      })
      
    },
    getAgent(){
      let req = {
        userType:'01'
      }
      getAgentList(req).then(res=>{
        if(res.code == 200){
          this.agentList = res.rows.map(e=>{
            return{
              label:e.nickName,
              value:e.userId
            }
          })
        }
      })
    },
    getList() {
      this.loading = true;
      getTerminalList(this.queryParams).then(response => {
        this.list = response.rows
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams =  {
        pageNum: 1,
        pageSize: 10,
        params:{}
      }
      this.handleQuery();
    },
    handleSelectionChange(val){
      this.selection = val
    },
    add(){
      this.form = {}
      this.open = true;
      this.title = "新增终端";
    },
    edit(row){
      this.form = row
      this.open = true;
      this.title = "修改终端";
    },
    edit1(){
      if(!this.selection.length){
        this.$message.warning('请选择一个终端')
        return
      }
      if(this.selection.length > 1){
        this.$message.warning('只能选择一个终端')
        return
      }
      this.form = this.selection[0]
      this.open = true;
      this.title = "修改终端";
    },
    del(row){
      this.selection = [row]
      this.delVisible = true
    },
    delbatch(){
      if(!this.selection.length){
        this.$message.warning('请选择一个终端')
        return
      }
      this.delVisible = true
    },
    delConfirm(){
      this.delVisible = false
      let ids = this.selection.map(e=>e.id).join(',')
      delTerminal(ids).then(res=>{
        if(res.code == 200){
          this.$message.success('删除成功')
          this.getList()
        }
      })
    },
    cancel() {
      this.form = {}
      this.open = false;
    },
    bindcancel(){
      this.form1= {}
      this.open1 = false;
    },
    bindTerminal(){
      this.open1 = true;
      this.form1 = {}
      this.terminalSelection = []
      this.remoteMethod()
    },
    bindConfirm(){
      this.$refs["form1"].validate(valid => {
        if (valid) {
          if(!this.terminalSelection){
            this.$message.warning('请选择绑定终端')
            return
          }
          this.form1.terminalIds = this.terminalSelection.join(',')
          this.form1.discount = this.form1.discount/100
          bindTerminal(this.form1).then(res=>{
            if(res.code == 200){
              this.$modal.msgSuccess("绑定成功");
              this.open1 = false;
            }
          })
        }
      });
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateTerminal(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTerminal(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    look(item){
      getTerminalCode(item.terminalNo).then(res=>{
        this.qrterminalCode = item.terminalNo
        this.openCode = true
        var url = window.URL.createObjectURL( new Blob([res],{type:'image/png;'}))
        this.vSrc = url
      })
    }
  }
};
</script>

<style lang="scss" scoped>
.warnStatus{
  display: flex;
  justify-content: center;
}
.circle{
  width: 8px;
  height: 8px;
  border-radius: 50%;
}
.terminalContent{
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 40px;
  .terminalItem{
    width: 50%;
  }
}
.dealContent{
  display: flex;
  align-items: center;
  height: 40px;
}
</style>

